package com.aura.springbook.common.exception;

import com.aura.springbook.common.R;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理器
 * <p>
 * 统一处理控制器中未捕获的异常，返回标准化的错误响应
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 处理运行时异常
     *
     * @param e 运行时异常
     * @return 错误响应
     */
    @ExceptionHandler(RuntimeException.class)
    public R<String> handleRuntimeException(RuntimeException e) {
        logger.error("运行时异常：{}", e.getMessage(), e);
        return R.fail(ResultCode.SYSTEM_ERROR, "系统运行时错误: " + e.getMessage());
    }

    /**
     * 处理通用异常
     *
     * @param e 通用异常
     * @return 错误响应
     */
    @ExceptionHandler(Exception.class)
    public R<String> handleException(Exception e) {
        logger.error("系统异常：{}", e.getMessage(), e);
        return R.fail(ResultCode.SYSTEM_ERROR, "系统内部错误: " + e.getMessage());
    }
}